package com.finiac.controller;



import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.finiac.dao.BillDAO;
import com.finiac.dao.PartialPaymentDAO;
import com.finiac.dao.ProductDAO;
import com.finiac.dao.SalesDAO;
import com.finiac.dao.StockAlertSettingsDAO;
import com.finiac.dao.StudentDAO;

import com.finiac.model.Bill;
import com.finiac.model.PartialPayment;
import com.finiac.model.Product;
import com.finiac.model.Sales;
import com.finiac.model.StockAlertSettings;
import com.finiac.model.Student;


public class PointOfSaleController extends MultiActionController {

	SalesDAO salesDAO;
	ProductDAO productDAO;
	BillDAO billDAO;
	PartialPaymentDAO partialPaymentDAO;
	StudentDAO studentDAO;
	StockAlertSettingsDAO stockAlertSettingsDAO;
	
	public void setStockAlertSettingsDAO(StockAlertSettingsDAO stockAlertSettingsDAO) {
		this.stockAlertSettingsDAO = stockAlertSettingsDAO;
	}

	public void setStudentDAO(StudentDAO studentDAO) {
		this.studentDAO = studentDAO;
	}

	public void setPartialPaymentDAO(PartialPaymentDAO partialPaymentDAO) {
		this.partialPaymentDAO = partialPaymentDAO;
	}

	public void setBillDAO(BillDAO billDAO) {
		this.billDAO = billDAO;
	}

	public void setSalesDAO(SalesDAO salesDAO) {
		this.salesDAO = salesDAO;
	}
	
	public void setProductDAO(ProductDAO productDAO) {
		this.productDAO = productDAO;
	}
	
	public ModelAndView createNewBill(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
	//	final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        final Calendar c = Calendar.getInstance();
        long billId;
        int month;
        Bill bill1 = new Bill();
        Sales sales= new Sales();
        String dateInFormat;
        month=c.get(Calendar.MONTH)+1;
        if(month<10)
        	dateInFormat="0"+month+"/";
        else
        	dateInFormat=month+"/";
        if(c.get(Calendar.DAY_OF_MONTH)<10) // value of month starts fro         
        	dateInFormat+="0"+c.get(Calendar.DAY_OF_MONTH)+"/";
        else
        	dateInFormat+=c.get(Calendar.DAY_OF_MONTH)+"/";
        
	    dateInFormat+= c.get(Calendar.YEAR);
	    if(request.getSession().getAttribute("billId")!=null)
	    {
	    	float amount=0;
	    	billId=Long.parseLong(request.getSession().getAttribute("billId").toString());
	    	System.out.println("control in " +billId);
	    	List<Sales> salesList= salesDAO.selectByBillId(billId);
	    	for(int i=0;i<salesList.size();i++)
			{
				sales = salesList.get(i);
				amount+=sales.getTotal();
			}	
	    	bill1=billDAO.selectBill(billId);
	    	bill1.setAmount(amount);
	    	billDAO.updateBill(bill1);
	    }
		Bill bill= new Bill(0, dateInFormat);
		billId= billDAO.createBill(bill);
		request.getSession().setAttribute("billId", billId);
		return new ModelAndView("redirect:listBill.htm"); 
	}
	public ModelAndView newBill(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		float qtySold,total,price;
		int productId;
		long billId;
		Product product = new Product();
		try{
			qtySold=Float.parseFloat(request.getParameter("qtySold"));
			price=Float.parseFloat(request.getParameter("price"));
			productId=Integer.parseInt(request.getParameter("productId"));
		}catch(NullPointerException e){
			qtySold=0;
			price=0;
			productId=0;
			System.out.println("Null pointer eexception");
		}
		
		total=qtySold*price;
		List<Product> productList= productDAO.selectById(productId);
		for(int i=0;i<productList.size();i++)
		{
			product = productList.get(i);
		}
		float temp= product.getQtyAvail();
		if(qtySold == 0)
			return new ModelAndView("redirect:listBill.htm?noQty=true");
		if(temp<qtySold || temp == 0)
		{
			return new ModelAndView("redirect:listBill.htm?noStock="+(temp-qtySold));
		   
		}
		else
		{
			product.setQtyAvail(temp-qtySold);
			productDAO.updateProduct(product);
			StockAlertSettings stockAlertLimit;
			String stockAlertString="";
			try{
				 stockAlertLimit = stockAlertSettingsDAO.getSettings();
			}catch (NullPointerException e) {
				StockAlertSettings settings= new StockAlertSettings();
				settings.setVariable("min_qty");
				settings.setValue("10");
				stockAlertLimit = stockAlertSettingsDAO.getSettings();
			}
	  		if(product.getQtyAvail()< Float.parseFloat(stockAlertLimit.getValue()))
	  			stockAlertString="stockAlert="+temp; 	 
			billId= Long.parseLong(request.getSession().getAttribute("billId").toString());
			Bill bill = new Bill();
			bill= billDAO.selectBill(billId);
			Sales sales= new Sales(product, qtySold, total,bill ,1); //Sales(Product productId, float qtySold, float total, long billId , int isActive)
			salesDAO.newSalesEntry(sales);	
			return new ModelAndView("redirect:listBill.htm?"+stockAlertString);
		}

		
	}
	
	public ModelAndView listBill(HttpServletRequest request, HttpServletResponse response)throws Exception
	{	
		long billId;
		billId= Long.parseLong(request.getSession().getAttribute("billId").toString());
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("items", salesDAO.getSalesEntries(billId));
		modelMap.addAttribute("bill", new Sales());
		return new ModelAndView("newBill",modelMap);
	}
	
	public ModelAndView stockAlertPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		StockAlertSettings stockAlert = new StockAlertSettings();
		stockAlert = stockAlertSettingsDAO.getSettings();
		return new ModelAndView("stockAlertSettings", "settings", stockAlert);
	}
	public ModelAndView updateStockAlertSettings(HttpServletRequest request, HttpServletResponse response, StockAlertSettings settings)throws Exception
	{
		stockAlertSettingsDAO.updateSettings(settings);
		return new ModelAndView("redirect:stockAlertPage.htm?success=yes");
	}
	
	public ModelAndView autoComplete(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		String text=request.getParameter("queryString");
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("productList",productDAO.autoCom(text));
		modelMap.addAttribute("product", new Product());
		return new ModelAndView("autoCompleteProducts",modelMap);
		
	}
	
	public ModelAndView deleteSalesEntry(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		int id=Integer.parseInt(request.getParameter("id"));
		float qtySold,qtyAvail;
		Product productId;
		Sales sales= new Sales();
		List<Sales> salesList= salesDAO.selectById(id);
		for(int i=0;i<salesList.size();i++)
		{
			sales = salesList.get(i);
		}
		sales.setIsActive(0);
		qtySold = sales.getQtySold();
		productId=sales.getProductId();
		qtyAvail=productId.getQtyAvail();
		productId.setQtyAvail(qtyAvail+qtySold);
		productDAO.updateProduct(productId);
		salesDAO.updateSalesEntry(sales);
		return new ModelAndView("redirect:listBill.htm");
	}
	public ModelAndView viewPrevBill(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		ModelMap modelMap = new ModelMap();
		if(request.getParameter("billNo") !=null)
		{
			long billId=Long.parseLong(request.getParameter("billNo"));
			System.out.println(billId);
			modelMap.addAttribute("items", salesDAO.selectByBillId(billId));
		}
		
		modelMap.addAttribute("bill", new Sales());
		return new ModelAndView("prevEntry",modelMap);
	}
	public ModelAndView lastEntry(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long billId= billDAO.lastBillId();
		return new ModelAndView("redirect:viewPrevBill.htm?billNo="+billId);
	}
	public ModelAndView autoComStudent(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long admissionNo= Long.parseLong(request.getParameter("adNo"));
		Student student = new Student();
		student= studentDAO.selectByAdmissionNo(admissionNo);
		return new ModelAndView("autoCompleteStudent", "student", student);
	}
	public ModelAndView listPartialPay(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		if(request.getSession().getAttribute("billId")!=null)  // to update total field of bill table of request is comming
	    {		System.out.println("control in ");											 // from add new list;
	    	float amt=0;
	    	long billId;
	    	Sales sales= new Sales();
	    	Bill bill1= new Bill();
	    	billId=Long.parseLong(request.getSession().getAttribute("billId").toString());
	    	System.out.println("control in " +billId);
	    	List<Sales> salesList= salesDAO.selectByBillId(billId);
	    	for(int i=0;i<salesList.size();i++)
			{
				sales = salesList.get(i);
				amt+=sales.getTotal();
			}	
	    	bill1=billDAO.selectBill(billId);
	    	bill1.setAmount(amt);
	    	billDAO.updateBill(bill1);
	    }
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("items", partialPaymentDAO.listAll());
		modelMap.addAttribute("partialPay", new PartialPayment());
		return new ModelAndView("partialPayment",modelMap);
	}
	public ModelAndView addPartialPay(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long billNo =Long.parseLong(request.getParameter("billNo"));
		long admissionNo=Long.parseLong(request.getParameter("admissionNo"));
		float amount = Long.parseLong(request.getParameter("amount"));
		float balanceAmt;
		Bill bill= new Bill();
		Student student= new Student();
		bill=billDAO.selectBill(billNo);
		student=studentDAO.selectByAdmissionNo(admissionNo);
		balanceAmt=bill.getAmount()-amount;
		PartialPayment pay = new PartialPayment(student, bill, balanceAmt);
		partialPaymentDAO.addDetails(pay);
		return new ModelAndView("redirect:listPartialPay.htm");
	}
	public ModelAndView updatePartialPayPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long id=Long.parseLong(request.getParameter("id"));
		PartialPayment partialPay = new PartialPayment();
		partialPay= partialPaymentDAO.selectById(id);
		if(request.getParameter("from").equals("search"))
			request.getSession().setAttribute("from",partialPay.getStudentId().getId());
		else
			request.getSession().setAttribute("from","main");
		return new ModelAndView("updatePartialPay", "partialPay", partialPay);
	}
	public ModelAndView updatePartialPay(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		float newAmount = Float.parseFloat(request.getParameter("newAmount"));
		long id=Long.parseLong(request.getParameter("partialPayId"));
		PartialPayment partialPay = new PartialPayment();
		partialPay= partialPaymentDAO.selectById(id);
		if(partialPay.getAmount()> newAmount)
			partialPay.setAmount(partialPay.getAmount()-newAmount);
		partialPaymentDAO.addDetails(partialPay);
		if(partialPay.getAmount()== newAmount)
			partialPaymentDAO.deletePartialPay(id);
		if(request.getSession().getAttribute("from").equals("main"))
			return new ModelAndView("redirect:listPartialPay.htm");
		return new ModelAndView("redirect:searchPartialPay.htm?studentId="+request.getSession().getAttribute("from"));
	}
	public ModelAndView deletePartialPay(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long id=Long.parseLong(request.getParameter("id"));
		partialPaymentDAO.deletePartialPay(id);
		return new ModelAndView();
	}
	public ModelAndView searchPartialPay(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long studentId;
		if(request.getParameter("studentId")==null)
			studentId=0;
		else
			studentId=Long.parseLong(request.getParameter("studentId"));
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("items", partialPaymentDAO.selectByStudent(studentId));
		modelMap.addAttribute("partialPay", new PartialPayment());
		return new ModelAndView("searchPartialPay",modelMap);
		
	}
	public ModelAndView printBill(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long id=Long.parseLong(request.getParameter("billNo"));
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("salesList", salesDAO.selectByBillId(id));
		modelMap.addAttribute("bill", billDAO.selectBill(id));
	
		return new ModelAndView("printBill", modelMap);
	}
}
